/*
 * =====================================================================================
 *
 *       Filename:  dispatcherThread.h
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  08/06/2012 08:22:28 PM
 *       Revision:  none
 *       Compiler:  gcc/g++
 *
 *         Author:  wangtengchao , wangtengchao AT gmail.com
 *   Organization:
 *
 * =====================================================================================
 */
#include "dispatcher.h"
#include "../concurrency/thread.h"
#include<boost/bind.hpp>
#ifdef NET_DEBUG
#include <cstdio>
#endif
namespace inm
{
    namespace net
    {
        class DispatcherThread
        {
        public:
            DispatcherThread(int i):
                threadId_(i),
                pDispatcher_(NULL),
                thread_(boost::bind(&DispatcherThread::threadFunc,this)),
                mutex_(),
                isStarted(false)
            {}
            ~DispatcherThread()
            {

                thread_.join();
                if(pDispatcher_ != NULL)
                    delete pDispatcher_;
            }
            void quit()
            {
                if(pDispatcher_ != NULL)
                    pDispatcher_->quit();
            }

            void threadFunc()
            {

                Dispatcher _dispatcher;
                pDispatcher_ = &_dispatcher;
                _dispatcher.handleEvents();
            }

            Dispatcher* getDispatcher() const
            {
                return pDispatcher_;
            }

            void start()
            {
                isStarted = true;
                thread_.start();
            }

        private:
            int threadId_;//for convient debug
            Dispatcher* pDispatcher_;
            inm::concurrency::Thread thread_;
            inm::concurrency::MutexLock mutex_;
            bool isStarted;//when first Task
        };
    };
};
